<template>
  <div class="doctor-management-container">
    <!-- 顶部标题栏 -->
    <div class="page-header">
      <div class="header-left">
        <div class="header-line"></div>
        <h1 class="page-title">医生管理</h1>
      </div>
      <div class="header-actions">
        <el-button class="action-btn export-btn" @click="exportToExcel">导出</el-button>
          <el-dropdown @command="handleImportCommand">
          <el-button class="action-btn export-btn">
            <el-icon><Upload /></el-icon>
            导入
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="import">
                <el-icon><Upload /></el-icon>
                导入Excel文件
              </el-dropdown-item>
              <el-dropdown-item command="template">
                <el-icon><Download /></el-icon>
                下载导入模板
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button class="action-btn delete-btn" @click="handleBatchDelete">删除</el-button>
        <el-button class="action-btn primary-btn" @click="openAddDialog">新增医生信息</el-button>
      </div>
      <div class="user-avatar">
        <el-avatar :size="40" style="background-color: #409EFF;">
          <el-icon><User /></el-icon>
        </el-avatar>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :inline="true" :model="formInline" class="search-form">
          <el-form-item>
            <el-cascader
              v-model="formInline.departmentId"
              :options="options"
              :props="props1"
              placeholder="请选择科室"
              class="search-select"
            />
          </el-form-item>
          <el-form-item>
            <el-input 
              v-model="formInline.doctorName" 
              placeholder="请输入医生姓名" 
              clearable 
              class="search-input"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchDoctorList" class="search-btn">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <el-table 
          :data="tableData" 
          class="doctor-table"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="doctorName" label="医生姓名" width="120" />
          <el-table-column prop="doctorPicture" label="医生头像" width="100">
            <template v-slot="scope">
              <el-avatar 
                :size="40" 
                :src="scope.row.doctorPicture"
                style="background-color: #E6F7FF;"
              >
                <el-icon><User /></el-icon>
              </el-avatar>
            </template>
          </el-table-column>
          <el-table-column prop="hospitalCampus" label="院区" width="100" />
          <el-table-column prop="professionalTitle" label="职称" width="120" />
          <el-table-column prop="departmentName" label="科室" width="150" />
          <el-table-column prop="doctorTag" label="标签" width="200">
            <template v-slot="scope">
              <div class="tag-container">
                <el-tag 
                  v-for="tag in getDoctorTags(scope.row.doctorTag)" 
                  :key="tag"
                  :type="getTagType(tag)"
                  size="small"
                  class="doctor-tag"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="doctorIntroduce" label="医生简介" min-width="200">
            <template v-slot="scope">
              <div class="doctor-intro">
                {{ scope.row.doctorIntroduce || '暂无简介' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template v-slot="scope">
              <div class="action-buttons">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="Update(scope.row)"
                  class="action-icon-btn edit-btn"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="Shan(scope.row.doctorId)"
                  class="action-icon-btn delete-icon-btn"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="page.pageIndex"
          v-model:page-size="page.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          prev-text="上一页" 
          next-text="下一页"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.totalCount"
          class="pagination"
        />
      </div>
    </div>
  </div>

  <!-- 新增弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    title="新增医生"
    width="500"
  >
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    label-width="auto"
  >
    <!-- 医生名称 -->
    <el-form-item label="医生名称" prop="doctorName">
      <el-input v-model="ruleForm.doctorName" />
    </el-form-item>

    <!-- 医生图片 -->
    <el-form-item label="医生图片" prop="doctorPicture"> <!-- 修复label错误（原"科室名称"） -->
      <el-upload
        class="avatar-uploader"
        action="http://localhost:5103/api/Manage/Imgs"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="ruleForm.doctorPicture" :src="ruleForm.doctorPicture" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>

    <!-- 所属院区 -->
    <el-form-item label="所属院区" prop="hospitalCampus">
      <el-select v-model="ruleForm.hospitalCampus" placeholder="请选择">
        <el-option label="东院区" value="东院区" />
        <el-option label="北院区" value="北院区" />
        <el-option label="湘南院区" value="湘南院区" />
      </el-select>
    </el-form-item>

    <!-- 所属科室 -->
    <el-form-item label="所属科室" prop="departmentId">
      <el-cascader
        v-model="ruleForm.departmentId"
        :options="options"
        :props="props1"
      />
    </el-form-item>

    <!-- 医生职称（修复选项错误） -->
    <el-form-item label="医生职称" prop="professionalTitle">
      <el-select v-model="ruleForm.professionalTitle" placeholder="请选择">
        <el-option label="主治医生" value="主治医生" />
        <el-option label="副主任医师" value="副主任医师" /> <!-- 修复错误选项 -->
        <el-option label="主任医师" value="主任医师" /> <!-- 补充合理选项 -->
      </el-select>
    </el-form-item>

    <!-- 医生标签 -->
    <el-form-item label="医生标签" prop="doctorTag">
      <el-checkbox-group v-model="ruleForm.doctorTag">
        <el-checkbox value="肝功能" name="doctorTag">肝功能</el-checkbox>
        <el-checkbox value="肾功能" name="doctorTag">肾功能</el-checkbox>
        <el-checkbox value="心脑血管" name="doctorTag">心脑血管</el-checkbox>
        <el-checkbox value="泌尿学科" name="doctorTag">泌尿学科</el-checkbox>
        <el-checkbox value="心脏病" name="doctorTag">心脏病</el-checkbox>
      </el-checkbox-group>
    </el-form-item>

    <!-- 挂号费 -->
    <el-form-item label="挂号费" prop="registrationFee">
      <el-input v-model="ruleForm.registrationFee" type="number" /> <!-- 限制为数字 -->
    </el-form-item>

    <!-- 诊查费 -->
    <el-form-item label="诊查费" prop="diagnosticFee">
      <el-input v-model="ruleForm.diagnosticFee" type="number" /> <!-- 限制为数字 -->
    </el-form-item>

    <!-- 医生简介 -->
    <el-form-item label="医生简介" prop="doctorIntroduce">
      <el-input v-model="ruleForm.doctorIntroduce" type="textarea" />
    </el-form-item>

    <!-- 医生状态 -->
    <el-form-item label="医生状态" prop="doctorStatus">
      <el-switch v-model="ruleForm.doctorStatus" />
    </el-form-item>

    <!-- 提交按钮 -->
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
      <el-button @click="cancelForm">取消</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>

  <el-dialog
    v-model="UpdatedialogVisible"
    title="修改医生"
    width="500"
  >
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    label-width="auto"
  >
    <!-- 医生名称 -->
    <el-form-item label="医生名称" prop="doctorName">
      <el-input v-model="ruleForm.doctorName" />
    </el-form-item>

    <!-- 医生图片 -->
    <el-form-item label="医生图片" prop="doctorPicture"> <!-- 修复label错误（原"科室名称"） -->
      <el-upload
        class="avatar-uploader"
        action="http://localhost:5103/api/Manage/Imgs"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="ruleForm.doctorPicture" :src="ruleForm.doctorPicture" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>

    <!-- 所属院区 -->
    <el-form-item label="所属院区" prop="hospitalCampus">
      <el-select v-model="ruleForm.hospitalCampus" placeholder="请选择">
        <el-option label="东院区" value="东院区" />
        <el-option label="北院区" value="北院区" />
        <el-option label="湘南院区" value="湘南院区" />
      </el-select>
    </el-form-item>

    <!-- 所属科室 -->
    <el-form-item label="所属科室" prop="departmentId">
      <el-cascader
        v-model="ruleForm.departmentId"
        :options="options"
        :props="props1"
      />
    </el-form-item>

    <!-- 医生职称（修复选项错误） -->
    <el-form-item label="医生职称" prop="professionalTitle">
      <el-select v-model="ruleForm.professionalTitle" placeholder="请选择">
        <el-option label="主治医生" value="主治医生" />
        <el-option label="副主任医师" value="副主任医师" /> <!-- 修复错误选项 -->
        <el-option label="主任医师" value="主任医师" /> <!-- 补充合理选项 -->
      </el-select>
    </el-form-item>

    <!-- 医生标签 -->
    <el-form-item label="医生标签" prop="doctorTag">
      <el-checkbox-group v-model="ruleForm.doctorTag">
        <el-checkbox value="肝功能" name="doctorTag">肝功能</el-checkbox>
        <el-checkbox value="肾功能" name="doctorTag">肾功能</el-checkbox>
        <el-checkbox value="心脑血管" name="doctorTag">心脑血管</el-checkbox>
        <el-checkbox value="泌尿学科" name="doctorTag">泌尿学科</el-checkbox>
        <el-checkbox value="心脏病" name="doctorTag">心脏病</el-checkbox>
      </el-checkbox-group>
    </el-form-item>

    <!-- 挂号费 -->
    <el-form-item label="挂号费" prop="registrationFee">
      <el-input v-model="ruleForm.registrationFee" type="number" /> <!-- 限制为数字 -->
    </el-form-item>

    <!-- 诊查费 -->
    <el-form-item label="诊查费" prop="diagnosticFee">
      <el-input v-model="ruleForm.diagnosticFee" type="number" /> <!-- 限制为数字 -->
    </el-form-item>

    <!-- 医生简介 -->
    <el-form-item label="医生简介" prop="doctorIntroduce">
      <el-input v-model="ruleForm.doctorIntroduce" type="textarea" />
    </el-form-item>

    <!-- 医生状态 -->
    <el-form-item label="医生状态" prop="doctorStatus">
      <el-switch v-model="ruleForm.doctorStatus" />
    </el-form-item>

    <!-- 提交按钮 -->
    <el-form-item>
      <el-button type="primary" @click="(UpdatesubmitForm)">修改</el-button>
      <el-button @click="cancelForm">取消</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>

  <!-- 导入进度对话框 -->
  <el-dialog
    v-model="importProgressVisible"
    title="导入进度"
    width="500"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <div class="import-progress-container">
      <div class="progress-info">
        <p>正在导入医生数据，请稍候...</p>
        <p class="progress-text">{{ importProgress.current }} / {{ importProgress.total }}</p>
      </div>
      <el-progress 
        :percentage="importProgress.percentage" 
        :status="importProgress.status"
        :stroke-width="8"
      />
      <div class="progress-details">
        <p>成功: {{ importProgress.success }} 条</p>
        <p>失败: {{ importProgress.error }} 条</p>
      </div>
    </div>
    <template #footer>
      <el-button 
        v-if="importProgress.status === 'success' || importProgress.status === 'exception'"
        type="primary" 
        @click="closeImportProgress"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { dataRead, dataWrite } from '@/Utils/Http';
import { onMounted, reactive, ref, watch } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Plus, User, Edit, Delete, Upload, Download, ArrowDown } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import * as XLSX from 'xlsx'

// 表格数据
const tableData = ref<any>([])
const selectedRows = ref<any>([])
const page = reactive({
  pageIndex: 1,
  pageSize: 5,
  totalCount: 0,
  pageCount: 0,
})
const formInline = reactive({
  doctorName: '',
  departmentId: '',
})

// 导入进度相关
const importProgressVisible = ref(false)
const importProgress = reactive({
  current: 0,
  total: 0,
  success: 0,
  error: 0,
  percentage: 0,
  status: 'normal' as 'normal' | 'success' | 'exception'
})

// 监听分页变化
watch(page, () => {
  fetchDoctorList()
})

// 初始化加载
onMounted(() => {
  fetchDoctorList()
  fetchDepartments()
  
})

// 获取医生列表
const fetchDoctorList = () => {
  dataRead.get("/Manage/DoctorShow", {
    params: {
      pageIndex: page.pageIndex,
      pageSize: page.pageSize,
      doctorName:formInline.doctorName,
      departmentId:formInline.departmentId,
    }
  }).then(res => {
    tableData.value = res.data.data.data;
    page.totalCount = res.data.data.totalCount;
    page.pageCount = res.data.data.pageCount;
  })
}

// 表单相关
const ruleFormRef = ref<FormInstance>()
const dialogVisible = ref(false)
const ruleForm = ref({
  doctorId: '',
  doctorName: "",
  doctorPicture: "",
  hospitalCampus: "",
  departmentId: "",
  professionalTitle: "",
  doctorTag: [] as string[], // 明确为字符串数组
  registrationFee: "",
  diagnosticFee: "",
  doctorIntroduce: "",
  doctorStatus: true,
  isdelete: false
})

// 打开新增弹窗
const openAddDialog = () => {
  // 重置表单
  ruleForm.value = {
    doctorId: '',
    doctorName: "",
    doctorPicture: "",
    hospitalCampus: "",
    departmentId: "",
    professionalTitle: "",
    doctorTag: [],
    registrationFee: "",
    diagnosticFee: "",
    doctorIntroduce: "",
    doctorStatus: true,
    isdelete: false
  }
  dialogVisible.value = true
}

// 图片上传成功回调
const handleAvatarSuccess = (response: any) => {
  // 假设接口返回的图片地址是response.data（根据实际接口调整）
  ruleForm.value.doctorPicture = response.data || response;
}

// 图片上传校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!['image/jpeg', 'image/png'].includes(rawFile.type)) { // 增加png支持
    ElMessage.error('请上传JPG或PNG格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      // 关键修复：将标签数组转换为字符串（用逗号分隔）
      const formData = {
        ...ruleForm.value,
        doctorTag: ruleForm.value.doctorTag.join(',') // 数组转字符串t
      }
      dataWrite.post("/Manage/DoctorsAdd", formData)
        .then(res => {
          if (res.data.code === 300) {
            ElMessage.success(res.data.message)
            dialogVisible.value = false
            fetchDoctorList() // 重新加载列表
          } else {
            ElMessage.error(res.data.message)
          }
        })
        .catch(err => {
          ElMessage.error('请求失败，请稍后重试')
          console.error(err)
        })
    }
  })
}

// 取消表单
const cancelForm = () => {
  dialogVisible.value = false // 关闭弹窗即可，无需刷新页面
  UpdatedialogVisible.value = false // 关闭弹窗即可，无需刷新页面
}

// 科室级联数据
const options = ref([])
const fetchDepartments = () => {
  dataRead.get("/Manage/Handle")
    .then(res => {
      options.value = res.data.data || []
    })
}
const props1 = {
  checkStrictly: true,
  emitPath: false,
}


//删除
const Shan=(doctorId:any)=>{
  ElMessageBox.confirm(
    '确定删除吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      dataWrite.delete("/Manage/DoctorsDelete",{
        data:{
          doctorId:doctorId,
        }
      })
     .then(res=>{
      if(res.data.code==500)
     {
      ElMessage.success(res.data.message)
      fetchDoctorList()

     }
     else
     {
         ElMessage.error(res.data.message)
     }
     })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

const UpdatedialogVisible=ref(false);
const Update=(row:any)=>{
  ruleForm.value.doctorId=row.doctorId;
  ruleForm.value.doctorName=row.doctorName;
  ruleForm.value.hospitalCampus=row.hospitalCampus;
  ruleForm.value.doctorPicture=row.doctorPicture;
  ruleForm.value.departmentId=row.departmentId;
  ruleForm.value.professionalTitle=row.professionalTitle;
  ruleForm.value.doctorTag=row.doctorTag;
  ruleForm.value.registrationFee=row.registrationFee;
  ruleForm.value.diagnosticFee=row.diagnosticFee;
  ruleForm.value.doctorIntroduce=row.doctorIntroduce;
  ruleForm.value.doctorStatus=row.doctorStatus;
  ruleForm.value.isdelete=row.isdelete;
  UpdatedialogVisible.value=true;
}

const UpdatesubmitForm=()=>{
   dataWrite.put("/Manage/DoctorsUpdate",ruleForm.value)
     .then(res=>{
      if(res.data.code==400)
     {
      ruleForm.value={
        doctorId: '',
        doctorName: "",
        doctorPicture: "",
        hospitalCampus: "",
        departmentId: "",
        professionalTitle: "",
        doctorTag: [],
        registrationFee: "",
        diagnosticFee: "",
        doctorIntroduce: "",
        doctorStatus: true,
        isdelete: false
      }
      ElMessage.success(res.data.message)
      UpdatedialogVisible.value=false;
      fetchDoctorList()
     }
     else
     {
         ElMessage.error(res.data.message)
     }
     })
}

// 处理表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 批量删除功能
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的医生')
    return
  }
  
  ElMessageBox.confirm(
    `确定删除选中的 ${selectedRows.value.length} 个医生吗?`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 这里可以实现批量删除逻辑
      ElMessage.success('批量删除功能待实现')
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 处理医生标签显示
const getDoctorTags = (doctorTag: string) => {
  if (!doctorTag) return []
  return doctorTag.split(',').filter(tag => tag.trim())
}

// 获取标签类型（用于不同颜色）
const getTagType = (tag: string) => {
  const tagTypes: { [key: string]: string } = {
    '糖尿病': 'success',
    '尿毒症': 'warning', 
    '肾病': 'danger',
    '肝功能': 'info',
    '肾功能': 'success',
    '心脑血管': 'warning',
    '泌尿学科': 'info',
    '心脏病': 'danger'
  }
  return tagTypes[tag] || 'info'
}

// 导出Excel功能
const exportToExcel = async () => {
  try {
    ElMessage.info('正在导出数据，请稍候...')
    
    // 获取所有医生数据（不分页）
    const response = await dataRead.get("/Manage/DoctorShow", {
      params: {
        pageIndex: 1,
        pageSize: 9999, // 设置一个很大的数值来获取所有数据
      }
    })
    
    const allDoctors = response.data.data.data
    
    // 格式化数据为Excel格式
    const excelData = allDoctors.map((doctor: any) => ({
      '医生名称': doctor.doctorName,
      '所属院区': doctor.hospitalCampus,
      '医生职称': doctor.professionalTitle,
      '医生标签': doctor.doctorTag,
      '挂号费': doctor.registrationFee,
      '诊查费': doctor.diagnosticFee,
      '简介': doctor.doctorIntroduce,
      '医生状态': doctor.doctorStatus ? '在班' : '休息',
      '所属科室': doctor.departmentName,
      '医生ID': doctor.doctorId
    }))
    
    // 创建工作簿
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.json_to_sheet(excelData)
    
    // 设置列宽
    const colWidths = [
      { wch: 12 }, // 医生名称
      { wch: 12 }, // 所属院区
      { wch: 12 }, // 医生职称
      { wch: 20 }, // 医生标签
      { wch: 10 }, // 挂号费
      { wch: 10 }, // 诊查费
      { wch: 30 }, // 简介
      { wch: 10 }, // 医生状态
      { wch: 12 }, // 所属科室
      { wch: 10 }  // 医生ID
    ]
    ws['!cols'] = colWidths
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '医生信息')
    
    // 生成文件名（包含当前日期）
    const now = new Date()
    const dateStr = now.getFullYear() + 
                   String(now.getMonth() + 1).padStart(2, '0') + 
                   String(now.getDate()).padStart(2, '0') + '_' +
                   String(now.getHours()).padStart(2, '0') + 
                   String(now.getMinutes()).padStart(2, '0')
    const fileName = `医生信息_${dateStr}.xlsx`
    
    // 导出文件
    XLSX.writeFile(wb, fileName)
    
    ElMessage.success(`导出成功！共导出 ${allDoctors.length} 条医生信息`)
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请稍后重试')
  }
}

// 处理导入命令
const handleImportCommand = (command: string) => {
  if (command === 'import') {
    importFromExcel()
  } else if (command === 'template') {
    downloadImportTemplate()
  }
}

// 下载导入模板
const downloadImportTemplate = () => {
  try {
    // 创建模板数据
    const templateData = [
      {
        '医生名称': '张三',
        '所属院区': '东院区',
        '医生职称': '主治医生',
        '医生标签': '肝功能,肾功能',
        '挂号费': '10',
        '诊查费': '20',
        '简介': '擅长内科疾病诊治',
        '医生状态': '在班',
        '所属科室': '内科'
      },
      {
        '医生名称': '李四',
        '所属院区': '北院区',
        '医生职称': '副主任医师',
        '医生标签': '心脑血管',
        '挂号费': '15',
        '诊查费': '25',
        '简介': '心血管疾病专家',
        '医生状态': '在班',
        '所属科室': '心血管科'
      }
    ]
    
    // 创建工作簿
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.json_to_sheet(templateData)
    
    // 设置列宽
    const colWidths = [
      { wch: 12 }, // 医生名称
      { wch: 12 }, // 所属院区
      { wch: 12 }, // 医生职称
      { wch: 20 }, // 医生标签
      { wch: 10 }, // 挂号费
      { wch: 10 }, // 诊查费
      { wch: 30 }, // 简介
      { wch: 10 }, // 医生状态
      { wch: 12 }  // 所属科室
    ]
    ws['!cols'] = colWidths
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '医生信息模板')
    
    // 生成文件名
    const fileName = '医生信息导入模板.xlsx'
    
    // 导出文件
    XLSX.writeFile(wb, fileName)
    
    ElMessage.success('模板下载成功！请按照模板格式填写数据')
    
  } catch (error) {
    console.error('模板下载失败:', error)
    ElMessage.error('模板下载失败，请稍后重试')
  }
}

// 导入Excel功能
const importFromExcel = () => {
  // 创建文件输入元素
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.xlsx,.xls'
  input.style.display = 'none'
  
  input.onchange = async (event: any) => {
    const file = event.target.files[0]
    if (!file) return
    
    try {
      ElMessage.info('正在解析文件，请稍候...')
      
      // 读取文件
      const data = await file.arrayBuffer()
      const workbook = XLSX.read(data, { type: 'array' })
      
      // 获取第一个工作表
      const sheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[sheetName]
      
      // 转换为JSON格式
      const jsonData = XLSX.utils.sheet_to_json(worksheet)
      
      if (jsonData.length === 0) {
        ElMessage.warning('Excel文件中没有数据')
        return
      }
      
      // 验证数据格式
      const validationResult = validateImportData(jsonData)
      if (!validationResult.isValid) {
        ElMessage.error(`数据格式错误：${validationResult.errors.join(', ')}`)
        return
      }
      
      // 转换数据格式
      const importData = convertImportData(jsonData)
      
      // 确认导入
      ElMessageBox.confirm(
        `检测到 ${importData.length} 条医生数据，确定要导入吗？`,
        '确认导入',
        {
          confirmButtonText: '确定导入',
          cancelButtonText: '取消',
          type: 'info',
        }
      ).then(async () => {
        await batchImportDoctors(importData)
      }).catch(() => {
        ElMessage.info('已取消导入')
      })
      
    } catch (error) {
      console.error('导入失败:', error)
      ElMessage.error('文件解析失败，请检查文件格式')
    } finally {
      // 清理文件输入元素
      document.body.removeChild(input)
    }
  }
  
  // 触发文件选择
  document.body.appendChild(input)
  input.click()
}

// 验证导入数据
const validateImportData = (data: any[]) => {
  const errors: string[] = []
  const requiredFields = ['医生名称', '所属院区', '医生职称']
  
  data.forEach((row, index) => {
    const rowNum = index + 2 // Excel行号从2开始（第1行是标题）
    
    // 检查必填字段
    requiredFields.forEach(field => {
      if (!row[field] || row[field].toString().trim() === '') {
        errors.push(`第${rowNum}行缺少必填字段"${field}"`)
      }
    })
    
    // 检查院区字段
    if (row['所属院区'] && !['东院区', '北院区', '湘南院区'].includes(row['所属院区'])) {
      errors.push(`第${rowNum}行院区字段值无效，应为：东院区、北院区、湘南院区`)
    }
    
    // 检查职称字段
    if (row['医生职称'] && !['主治医生', '副主任医师', '主任医师'].includes(row['医生职称'])) {
      errors.push(`第${rowNum}行职称字段值无效，应为：主治医生、副主任医师、主任医师`)
    }
    
    // 检查数字字段
    if (row['挂号费'] && isNaN(Number(row['挂号费']))) {
      errors.push(`第${rowNum}行挂号费必须是数字`)
    }
    if (row['诊查费'] && isNaN(Number(row['诊查费']))) {
      errors.push(`第${rowNum}行诊查费必须是数字`)
    }
  })
  
  return {
    isValid: errors.length === 0,
    errors
  }
}

// 转换导入数据格式
const convertImportData = (data: any[]) => {
  return data.map(row => ({
    doctorName: row['医生名称']?.toString().trim() || '',
    hospitalCampus: row['所属院区']?.toString().trim() || '',
    professionalTitle: row['医生职称']?.toString().trim() || '',
    doctorTag: row['医生标签']?.toString().trim() || '',
    registrationFee: row['挂号费']?.toString().trim() || '',
    diagnosticFee: row['诊查费']?.toString().trim() || '',
    doctorIntroduce: row['简介']?.toString().trim() || '',
    doctorStatus: row['医生状态']?.toString().trim() === '在班' || true,
    departmentName: row['所属科室']?.toString().trim() || '',
    doctorPicture: '' // 导入时不包含图片，需要后续手动上传
  }))
}

// 批量导入医生数据
const batchImportDoctors = async (importData: any[]) => {
  try {
    // 初始化进度
    importProgress.current = 0
    importProgress.total = importData.length
    importProgress.success = 0
    importProgress.error = 0
    importProgress.percentage = 0
    importProgress.status = 'normal'
    importProgressVisible.value = true
    
    const errors: string[] = []
    
    // 逐个导入医生数据
    for (let i = 0; i < importData.length; i++) {
      try {
        const doctorData = importData[i]
        
        // 调用后端接口添加医生
        const response = await dataWrite.post("/Manage/DoctorsAdd", doctorData)
        
        if (response.data.code === 300) {
          importProgress.success++
        } else {
          importProgress.error++
          errors.push(`第${i + 1}条数据导入失败：${response.data.message}`)
        }
      } catch (error) {
        importProgress.error++
        errors.push(`第${i + 1}条数据导入失败：网络错误`)
      }
      
      // 更新进度
      importProgress.current = i + 1
      importProgress.percentage = Math.round(((i + 1) / importData.length) * 100)
      
      // 添加小延迟，让用户能看到进度变化
      await new Promise(resolve => setTimeout(resolve, 100))
    }
    
    // 设置最终状态
    if (importProgress.error === 0) {
      importProgress.status = 'success'
    } else if (importProgress.success === 0) {
      importProgress.status = 'exception'
    } else {
      importProgress.status = 'exception' // 部分成功也显示为异常状态
    }
    
    // 显示导入结果
    if (importProgress.success > 0) {
      ElMessage.success(`成功导入 ${importProgress.success} 条医生数据`)
      fetchDoctorList() // 刷新列表
    }
    
    if (importProgress.error > 0) {
      ElMessage.warning(`有 ${importProgress.error} 条数据导入失败`)
      console.error('导入错误详情:', errors)
    }
    
    // 如果有错误，显示详细错误信息
    if (errors.length > 0) {
      setTimeout(() => {
        ElMessageBox.alert(
          errors.slice(0, 10).join('\n') + (errors.length > 10 ? `\n...还有${errors.length - 10}个错误` : ''),
          '导入错误详情',
          {
            confirmButtonText: '确定',
            type: 'error'
          }
        )
      }, 1000)
    }
    
  } catch (error) {
    console.error('批量导入失败:', error)
    importProgress.status = 'exception'
    ElMessage.error('批量导入失败，请稍后重试')
  }
}

// 关闭导入进度对话框
const closeImportProgress = () => {
  importProgressVisible.value = false
  // 重置进度数据
  importProgress.current = 0
  importProgress.total = 0
  importProgress.success = 0
  importProgress.error = 0
  importProgress.percentage = 0
  importProgress.status = 'normal'
}
</script>

<style scoped>
/* 整体容器 */
.doctor-management-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

/* 顶部标题栏 */
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-line {
  width: 4px;
  height: 24px;
  background-color: #409EFF;
  margin-right: 12px;
  border-radius: 2px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.action-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
}

.export-btn, .delete-btn {
  background-color: #E6F7FF;
  color: #409EFF;
  border: 1px solid #91D5FF;
}

.export-btn:hover, .delete-btn:hover {
  background-color: #BAE7FF;
}

.primary-btn {
  background-color: #409EFF;
  color: white;
}

.primary-btn:hover {
  background-color: #337ECC;
}

.user-avatar {
  margin-left: 20px;
}

/* 主要内容区域 */
.main-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 24px;
}

/* 搜索区域 */
.search-section {
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-select, .search-input {
  width: 200px;
}

.search-select :deep(.el-input__wrapper) {
  border-radius: 4px;
  border: 1px solid #d9d9d9;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 4px;
  border: 1px solid #d9d9d9;
}

.search-btn {
  background-color: #409EFF;
  border-color: #409EFF;
  border-radius: 4px;
  padding: 8px 20px;
}

/* 表格区域 */
.table-section {
  margin-bottom: 24px;
}

.doctor-table {
  border-radius: 8px;
  overflow: hidden;
}

.doctor-table :deep(.el-table__header) {
  background-color: #fafafa;
}

.doctor-table :deep(.el-table__header th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
  border-bottom: 1px solid #e8e8e8;
}

.doctor-table :deep(.el-table__body tr) {
  transition: background-color 0.3s ease;
}

.doctor-table :deep(.el-table__body tr:hover) {
  background-color: #f5f7fa;
}

/* 标签容器 */
.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.doctor-tag {
  border-radius: 12px;
  font-size: 12px;
  padding: 2px 8px;
}

/* 医生简介 */
.doctor-intro {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #666;
  font-size: 14px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 8px;
}

.action-icon-btn {
  width: 32px;
  height: 32px;
  padding: 0;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit-btn {
  background-color: #409EFF;
  border-color: #409EFF;
}

.delete-icon-btn {
  background-color: #F56C6C;
  border-color: #F56C6C;
}

/* 分页区域 */
.pagination-section {
  display: flex;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.pagination {
  margin: 0;
}

/* 弹窗样式优化 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  background-color: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  border-radius: 8px 8px 0 0;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #333;
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 4px;
}

/* 上传组件样式 */
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 8px;
}

/* 导入进度对话框样式 */
.import-progress-container {
  padding: 20px 0;
}

.progress-info {
  text-align: center;
  margin-bottom: 20px;
}

.progress-info p {
  margin: 8px 0;
  color: #666;
}

.progress-text {
  font-size: 18px;
  font-weight: 600;
  color: #409EFF;
}

.progress-details {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.progress-details p {
  margin: 0;
  font-weight: 500;
}

.progress-details p:first-child {
  color: #67c23a;
}

.progress-details p:last-child {
  color: #f56c6c;
}

/* 下拉菜单样式优化 */
:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-dropdown-menu__item .el-icon) {
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-select, .search-input {
    width: 100%;
  }
}
</style>

<style>
/* 全局样式 */
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

/* 表格复选框样式 */
.el-table .el-checkbox {
  margin-right: 0;
}

/* 分页样式优化 */
.el-pagination {
  justify-content: center;
}

.el-pagination .el-pager li {
  border-radius: 4px;
  margin: 0 2px;
}

.el-pagination .el-pager li.is-active {
  background-color: #409EFF;
  color: white;
}

/* 按钮悬停效果 */
.el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 标签颜色自定义 */
.el-tag--success {
  background-color: #f0f9ff;
  color: #67c23a;
  border-color: #b3e19d;
}

.el-tag--warning {
  background-color: #fdf6ec;
  color: #e6a23c;
  border-color: #f5dab1;
}

.el-tag--danger {
  background-color: #fef0f0;
  color: #f56c6c;
  border-color: #fbc4c4;
}

.el-tag--info {
  background-color: #f4f4f5;
  color: #909399;
  border-color: #d3d4d6;
}
</style>